package com.huluobo.a2204kotlinjetpackdemo.paging

import android.util.Log
import androidx.paging.PagingSource
import androidx.paging.PagingState
import java.lang.Exception

/**
 *  Created by LC on 2024/8/19.
 */
class RepoPagingSource(val apiService: PagingApiService) : PagingSource<Int, GitPagingBean>() {
    override fun getRefreshKey(state: PagingState<Int, GitPagingBean>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, GitPagingBean> {
        return try {
            //4步发起网络请求
            val page = params.key ?: 1//当前的页码
            val pageSize = params.loadSize //当前页面中的item的数量
            val repoResponse = apiService.getPagingData(page, pageSize)//发起网络请求的返回值
            val repoItems = repoResponse.items //请求返回的数据源
            Log.i("TagA", "items:${repoItems.size}")

            val preKey = if (page > 1) page - 1 else null //向前翻页的页码,必须大于1
            val nextKey = if (repoItems.isNotEmpty()) page + 1 else null//向后翻页的页码,需要判断返回的数据源不能为空,为空代表已经没有数据了,再向后翻页也没有数据
            LoadResult.Page(repoItems, preKey, nextKey)//发起请求,返回成功,填入数据源和向前翻页的页码,和向后翻页的页码
        } catch (e: Exception) {
            LoadResult.Error(e)
        }
    }
}